package com.mocha.bss.domain.rbac.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import jakarta.annotation.PostConstruct;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * @author: songkui
 * @since: 2022/4/14 16:06
 */
@Component
@Slf4j
public class MochaFunctionListener {

    private ConfigService configService;


    @Value("${mocha.function.nacos.data-id}")
    private String dataId;

    @Value("${mocha.function.nacos.group}")
    private String group = "DEFAULT_GROUP";

    @Autowired
    private RPCHandler rpcHandler;
    @Autowired
    private MochaNacosProperties mochaNacosProperties;

    @PostConstruct
    public void init() {
        log.info("Server start role menu init...");
        try{
            configService = NacosFactory.createConfigService(mochaNacosProperties.buildNacosProperties());
            if(configService == null){
                log.warn("Server start InitConfigService fail *******");
                return;
            }
            long timeOut = 5000L;
            String configXml = configService.getConfig(dataId, group, timeOut);
            log.info("------- Server start loading role menu configInfo--------- \r\n{}",configXml);
            MenuXmlUtil.doFlushData(configXml);
        } catch (Exception e) {
            log.error("Server start Init role menu exception: {}", e);
        }
        dynamicByNacosListener(dataId, group);
    }

    //NacosListener
    private void dynamicByNacosListener (String dataId, String group){
        try {
            configService.addListener(dataId, group, new Listener()  {
                @SneakyThrows
                @Override
                public void receiveConfigInfo(String configXml) {
                    log.info("--------Newest role menuinfo--------- \n\r{}",configXml);
                    MenuXmlUtil.doFlushData(configXml);
                    log.info("Update  newest role menu start...");
                    rpcServer();
                }
                @Override
                public Executor getExecutor() {
                    log.info("getExecutor\n\r");
                    return null;
                }
            });
        } catch (NacosException e) {
            log.error("Listener to Nacos role menu exception: {}",e);
        }
    }

    private void rpcServer(){
        try {
            TimeUnit.SECONDS.sleep(1);
            rpcHandler.functionRoleServerAPI();
        } catch (InterruptedException e) {
            log.error("flush sleep：", e);
            rpcHandler.functionRoleServerAPI();
        }
    }


}
